package com.wjh.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang3.StringUtils;

import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author leiyuewei
 */
@Slf4j
public class ScPayKit {
	public static byte[] AES_KEY = "4ChT08phkz59hquD795X7w==".getBytes();

	/** 加密 **/
	public static String aesEncode(String str) {
		return SecureUtil.aes(ScPayKit.AES_KEY).encryptHex(str);
	}

	public static String aesDecode(String str) {
		return SecureUtil.aes(ScPayKit.AES_KEY).decryptStr(str);
	}

	private static String encodingCharset = "UTF-8";

	public static String getSign(Map<String, Object> map, String key) {
		ArrayList<String> list = new ArrayList<String>();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (null != entry.getValue() && !"".equals(entry.getValue())) {
				list.add(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		int size = list.size();
		String[] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(arrayToSort[i]);
		}
		String result = sb.toString();
		result += "key=" + key;
		log.info("signStr:{}", result);
		result = md5(result, encodingCharset).toUpperCase();
		log.info("sign:{}", result);
		return result;
	}

	public static String md5(String value, String charset) {
		MessageDigest md = null;
		try {
			byte[] data = value.getBytes(charset);
			md = MessageDigest.getInstance("MD5");
			byte[] digestData = md.digest(data);
			return toHex(digestData);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String toHex(byte input[]) {
		if (input == null) {
			return null;
		}
		StringBuffer output = new StringBuffer(input.length * 2);
		for (int i = 0; i < input.length; i++) {
			int current = input[i] & 0xff;
			if (current < 16) {
				output.append("0");
			}
			output.append(Integer.toString(current, 16));
		}

		return output.toString();
	}

	/** map 转换为 url参数 **/
	public static String genUrlParams(Map<String, Object> paraMap) {
		if (paraMap == null || paraMap.isEmpty()) {
			return "";
		}
		StringBuffer urlParam = new StringBuffer();
		Set<String> keySet = paraMap.keySet();
		int i = 0;
		for (String key : keySet) {
			urlParam.append(key).append("=")
					.append(paraMap.get(key) == null ? "" : doEncode(paraMap.get(key).toString()));
			if (++i == keySet.size()) {
				break;
			}
			urlParam.append("&");
		}
		return urlParam.toString();
	}

	static String doEncode(String str) {
		if (str.contains("+")) {
			return URLEncoder.encode(str);
		}
		return str;
	}

	public static String appendUrlQuery(String url, Map<String, Object> map) {

		if (StringUtils.isEmpty(url) || map == null || map.isEmpty()) {
			return url;
		}

		StringBuilder sb = new StringBuilder(url);
		if (url.indexOf("?") < 0) {
			sb.append("?");
		}

		// 是否包含query条件
		boolean isHasCondition = url.indexOf("=") >= 0;

		for (String k : map.keySet()) {
			if (k != null && map.get(k) != null) {
				if (isHasCondition) {
					// 包含了查询条件， 那么应当拼接&符号
					sb.append("&");
				} else {
					// 变更为： 已存在query条件
					isHasCondition = true;
				}
				sb.append(k).append("=").append(URLUtil.encodeQuery(map.get(k).toString()));
			}
		}
		return sb.toString();
	}

	private static final AtomicLong PAY_ORDER_SEQ = new AtomicLong(0L);

	/** 是否使用MybatisPlus生成分布式ID **/
	private static final boolean IS_USE_MP_ID = true;

	private static final String PAY_ORDER_SEQ_PREFIX = "P";
	private static final String REFUND_ORDER_SEQ_PREFIX = "R";
	private static final String MHO_ORDER_SEQ_PREFIX = "M";
	private static final String TRANSFER_ID_SEQ_PREFIX = "T";
	private static final String DIVISION_BATCH_ID_SEQ_PREFIX = "D";
}
